package com.itda.service.Impl;

import com.itda.mapper.DeptMapper;
import com.itda.mapper.EmpMapper;
import com.itda.pojo.Dept;
import com.itda.pojo.DeptLog;
import com.itda.service.DeptLogService;
import com.itda.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: itda
 * @Date: 2024/4/27 18:56
 * @Description: DeptServiceImpl
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {

        return deptMapper.list();
    }

    @Override
    //默认回滚运行时异常  通过rollbackFor属性来指定出现什么样的异常才进行回滚
    //@Transactional(rollbackFor = Exception.class)//spring事务管理
    //propagation属性的默认值是需要事务,有事务就加入事务 Propagation.REQUIRES_NEW是需要一个新事务
    @Transactional
    public void delete(Integer id) {
        try {
            deptMapper.deleteById(id);//根据id删除部门


            /*int i = 1/0;*/
            //根据部门的id来删除该部门下的员工
            empMapper.deleteByDeptId(id);
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作,此次解散的是" + id + "号部门");
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);
    }

    @Override
    public Dept query(Integer id) {
        return deptMapper.query(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
